package com.suning.park.admin.esb.service.impl;

import com.suning.park.admin.bean.Content;
import com.suning.park.admin.enums.YesOrNoEnum;
import com.suning.park.admin.esb.TA0301020501.MemberCardAccountMgmtService;
import com.suning.park.admin.esb.TA0301020501.dto.TA0301020501BodyReq;
import com.suning.park.admin.esb.TA0301020501.dto.TA0301020501Req;
import com.suning.park.admin.esb.TA04010350.MemberAccountMgmtService;
import com.suning.park.admin.esb.TA04010350.dto.TA04010350BodyReq;
import com.suning.park.admin.esb.TA04010350.dto.TA04010350Req;
import com.suning.park.admin.esb.TA04010360.MemberRollbackAccountService;
import com.suning.park.admin.esb.TA04010360.dto.TA04010360BodyReq;
import com.suning.park.admin.esb.TA04010360.dto.TA04010360Req;
import com.suning.park.admin.esb.TR01030020.CMFMemberInfoMgmtService;
import com.suning.park.admin.esb.TR01030020.dto.TR01030020Req;
import com.suning.park.admin.esb.TR01030020.dto.TR01030020Res;
import com.suning.park.admin.esb.TR03010952.OrderPointUseService;
import com.suning.park.admin.esb.TR03010952.dto.TR03010952BodyReq;
import com.suning.park.admin.esb.TR03010952.dto.TR03010952BodyRes;
import com.suning.park.admin.esb.TR03010952.dto.TR03010952Req;
import com.suning.park.admin.esb.TR03010952.dto.TR03010952Res;
import com.suning.park.admin.esb.TR04010100.PointAccountPointsMgmtService;
import com.suning.park.admin.esb.TR04010100.dto.TR04010100BodyReq;
import com.suning.park.admin.esb.TR04010100.dto.TR04010100Req;
import com.suning.park.admin.esb.TR04010100.dto.TR04010100Res;
import com.suning.park.admin.esb.service.IMemberService;
import com.suning.park.admin.exception.BusinessFailException;
import com.suning.park.admin.util.StringUtil;
import com.suning.rsc.RscException;
import com.suning.rsc.dto.responsedto.MbfResponse;
import com.suning.rsc.dto.responsedto.MbfServiceResponse;
import com.suning.rsc.httpservice.annotation.EsbEIHttpWired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;

/**
 * 会员相关服务
 * Created by Administrator on 2017/1/24.
 */
public class MemberServiceImpl implements IMemberService {

    private final static Logger logger = LoggerFactory.getLogger(MemberServiceImpl.class);


    private CMFMemberInfoMgmtService cmfMemberInfoMgmtService;

    private MemberAccountMgmtService memberAccountMgmtService;

    private PointAccountPointsMgmtService pointAccountPointsMgmtService;

    private MemberCardAccountMgmtService memberCardAccountMgmtService;

    private MemberRollbackAccountService memberRollbackAccountService;

    private OrderPointUseService orderPointUseService;


    /**
     * 根据手机号查询会员编号
     * @param phone
     * @return
     * @throws BusinessFailException
     */
    @Override
    public String queryCustNumByPhone(String phone) throws BusinessFailException {
        TR01030020Req req = new TR01030020Req(Content.TR01030020REQ_CODE);
        req.getBody().setAliasType(Content.ALIASTYPE);//别名类型  手机号
        req.getBody().setAliasName(phone);//手机号
        try {
            MbfResponse mbfResponse = cmfMemberInfoMgmtService.queryMemberType(req);
            validataRes(mbfResponse);
            TR01030020Res res = (TR01030020Res) mbfResponse.getOutput().getMbfBody(TR01030020Res.class);
            return res.getBody().getCustNum();
        } catch (RscException e) {
            logger.error("queryCustNumByPhone error ", e);
            throw new BusinessFailException("根据手机号查询会员编号失败");
        }
    }

    /**
     * 查询账户积分余额
     *
     * @param custNum    会员编号
     * @param branchCode 公司代码
     * @param storeCode  门店代码
     * @return
     * @throws BusinessFailException
     */
    @Override
    public double queryBalance(String custNum, String branchCode, String storeCode) throws BusinessFailException {
        TR04010100Req req = new TR04010100Req(Content.TR04010100REQ_CODE);
        TR04010100BodyReq body = new TR04010100BodyReq();
        body.setCustNum(custNum);
        body.setEcoType(Content.ECO_TYPE);
        body.setStore(storeCode);
        body.setBranch(branchCode);
        req.setBody(body);
        try {
            MbfResponse mbfResponse = pointAccountPointsMgmtService.queryPointsBalance(req);
            validataRes(mbfResponse);
            TR04010100Res res = (TR04010100Res) mbfResponse.getOutput().getMbfBody(TR04010100Res.class);
            return Double.parseDouble(res.getBody().getBasicValue()) + Double.parseDouble(res.getBody().getSalesValue());
        } catch (RscException e) {
            logger.error("queryBalance error ", e);
            throw new BusinessFailException("查询账号积分余额失败");
        }
    }

    /**
     * 创建线下会员
     *
     * @param custNum    易付宝会员编号(线上)
     * @param branchCode 分公司代码
     * @param storeCode  门店代码
     * @throws BusinessFailException
     */
    @Override
    public void createMember(String custNum, String branchCode, String storeCode) throws BusinessFailException {
        TA0301020501Req req = new TA0301020501Req(Content.TA0301020501REQ_CODE);
        TA0301020501BodyReq body = new TA0301020501BodyReq();
        body.setCustNum(custNum);
        body.setEcoType(Content.ECO_TYPE);
        body.setBranch(branchCode);
        body.setStore(storeCode);
        req.setBody(body);
        try {
            MbfResponse mbfResponse = memberCardAccountMgmtService.createMember(req);
            validataRes(mbfResponse);
        } catch (RscException e) {
            logger.error("createMember error ", e);
            throw new BusinessFailException("创建线下会员失败");
        }
    }

    /**
     * 会员云钻退货接口
     *
     * @param custNum     会员编号
     * @param branchCode  分公司代码
     * @param storeCode   门店代码
     * @param orderId     购物使用订单ID纯数字组合
     * @param backOrderId 退货订单ID 纯数字组合
     * @param amt         云钻数量
     */
    @Override
    public void accountReturnGoods(String custNum, String branchCode, String storeCode, String orderId, String backOrderId, String amt) {
        TA04010350Req req = new TA04010350Req(Content.TA04010350REQ_CODE);
        TA04010350BodyReq body = new TA04010350BodyReq();
        body.setCustNum(custNum);
        body.setEcoType(Content.ECO_TYPE);
        body.setOrderItemId(orderId);
        body.setBackOrderItemId(backOrderId);
        body.setStore(storeCode);
        body.setBranch(branchCode);
        body.setOperator(Content.APP_CODE);
        TA04010350BodyReq.AddStruct addStruct = new TA04010350BodyReq.AddStruct();
        addStruct.setAccountAddAmt(new BigDecimal(amt));
        addStruct.setAccountType(Content.ACCOUNT_TYPE);
        body.getAddStructList().add(addStruct);
        req.setBody(body);
        try {
            MbfResponse mbfResponse = memberAccountMgmtService.updateAccountResourceWhenReturnGoods(req);
            validataRes(mbfResponse);
        } catch (RscException e) {
            logger.error("accountReturnGoods error ", e);
            throw new BusinessFailException("会员退货失败");
        }
    }

    /**
     * 账户回滚操作
     *
     * @param custNum    会员编号
     * @param branchCode 分公司代码
     * @param storeCode  门店代码
     * @param orderId    购物使用订单ID/退货订单ID
     */
    @Override
    public void memberAccountRollback(String custNum, String branchCode, String storeCode, String orderId) {
        TA04010360Req req = new TA04010360Req(Content.TA04010360REQ_CODE);
        TA04010360BodyReq body = new TA04010360BodyReq();
        body.setCustNum(custNum);
        body.setEcoType(Content.ECO_TYPE);
        body.setStore(storeCode);
        body.setBranch(branchCode);
        body.setOperator(Content.APP_CODE);
        body.setOrderItemId(orderId);
        body.setOrderType(Content.ORDER_TYPE);//订单类型
        req.setBody(body);
        try {
            MbfResponse mbfResponse = memberRollbackAccountService.rollbackAccount(req);
            validataRes(mbfResponse);
        } catch (RscException e) {
            logger.error("memberAccountRollback error ", e);
            throw new BusinessFailException("账户回滚操作失败");
        }
    }

    /**
     * 会员积分购物使用
     *
     * @param custNum      会员编号
     * @param branchCode   分公司代码
     * @param storeCode    门店代码
     * @param transId      交易ID UUID
     * @param orderId      订单ID(需要时纯数字组成)长度最大20
     * @param amount       云钻数量
     * @param supplierCode C店商户积分发放主体编码
     * @return
     */
    @Override
    public void pointUse(String custNum, String branchCode, String storeCode, String transId, String orderId, BigDecimal amount, String supplierCode) {
        TR03010952Req req = new TR03010952Req(Content.TR03010952REQ_CODE);
        TR03010952BodyReq body = new TR03010952BodyReq();
        body.setTransId(transId);
        body.setInvokerCode(Content.APP_CODE);
        body.setSceneCode(Content.SCENECODE);
        body.setCustNum(custNum);
        body.setEcoType(Content.ECO_TYPE);
        TR03010952BodyReq.Order order = new TR03010952BodyReq.Order();
        order.setBranch(branchCode);
        order.setStore(storeCode);
//        String orderItemId = System.currentTimeMillis() + "" + (int) ((Math.random() * 9 + 1) * 100000);
        order.setOrderItemId(orderId);
        order.setOrderType(Content.ORDER_TYPE);//订单类型
        order.setOrderTypeDesc("苏宁广场停车费用支付");
        if(StringUtil.isNotBlank(supplierCode)){
            order.setSupplierType(Content.CLIENT_SUPPLIER_TYPE);//209000000020C店商户
        }else{
            order.setSupplierType(Content.SN_SUPPLIER_TYPE);//209000000010苏宁自营
        }
        order.setSupplierCode(supplierCode);
        TR03010952BodyReq.Subtract subtract = new TR03010952BodyReq.Subtract();
        subtract.setAccountType(Content.ACCOUNT_TYPE);
        subtract.setSubtractAmt(amount);
        order.getSubtractItem().add(subtract);
        body.getOrderItem().add(order);
        req.setBody(body);
        try {
            MbfResponse mbfResponse = orderPointUseService.pointUse(req);
            validataRes(mbfResponse);
            TR03010952Res res = (TR03010952Res) mbfResponse.getOutput().getMbfBody(TR03010952Res.class);
            TR03010952BodyRes.Order order1 = res.getBody().getOrderItem().get(0);
            logger.info("购物使用结果:{},{},{}", new Object[]{order1.getIsSucc(), order1.getOrderItemId(), order1.getErrorDesc()});
            if(!"Y".equals(order1.getIsSucc())){
                throw new BusinessFailException(order1.getErrorDesc());
            }
        } catch (RscException e) {
            logger.error("pointUse error ", e);
            throw new BusinessFailException("支付失败");
        }
    }





    /**
     * 根据会员编号查询会员类型
     *
     * @param custNum 会员编号
     * @return 0 个人会员   1团体会员
     */
    @Override
    public String queryMemberType(String custNum) throws BusinessFailException {
        TR01030020Req req = new TR01030020Req(Content.TR01030020REQ_CODE);
        req.getBody().setCustNum(custNum);
        try {
            MbfResponse mbfResponse = cmfMemberInfoMgmtService.queryMemberType(req);
            validataRes(mbfResponse);
            TR01030020Res res = (TR01030020Res) mbfResponse.getOutput().getMbfBody(TR01030020Res.class);
            if (Content.SIMPLE_PEOPLE.equals(res.getBody().getCustType())) {
                return YesOrNoEnum.YES.getValue();
            }
        } catch (RscException e) {
            logger.error("queryMemberType error ", e);
            throw new BusinessFailException("查询账号类型失败");
        }
        return YesOrNoEnum.NO.getValue();
    }


    /**
     * 验证返回信息
     *
     * @param mbfResponse
     * @throws BusinessFailException
     */
    private void validataRes(MbfResponse mbfResponse) throws BusinessFailException {
        if (!mbfResponse.isSucceed()) {
            MbfServiceResponse serviceResponse = mbfResponse.getOutput().getMbfHeader().getServiceResponse();
            logger.error("错误编码:{},错误信息:{}",serviceResponse.getCode(),serviceResponse.getDesc());
            throw new BusinessFailException(serviceResponse.getDesc());
        }
    }

    public MemberAccountMgmtService getMemberAccountMgmtService() {
        return memberAccountMgmtService;
    }

    @EsbEIHttpWired
    public void setMemberAccountMgmtService(MemberAccountMgmtService memberAccountMgmtService) {
        this.memberAccountMgmtService = memberAccountMgmtService;
    }

    public CMFMemberInfoMgmtService getCmfMemberInfoMgmtService() {
        return cmfMemberInfoMgmtService;
    }

    @EsbEIHttpWired
    public void setCmfMemberInfoMgmtService(CMFMemberInfoMgmtService cmfMemberInfoMgmtService) {
        this.cmfMemberInfoMgmtService = cmfMemberInfoMgmtService;
    }

    public PointAccountPointsMgmtService getPointAccountPointsMgmtService() {
        return pointAccountPointsMgmtService;
    }

    @EsbEIHttpWired
    public void setPointAccountPointsMgmtService(PointAccountPointsMgmtService pointAccountPointsMgmtService) {
        this.pointAccountPointsMgmtService = pointAccountPointsMgmtService;
    }

    public MemberCardAccountMgmtService getMemberCardAccountMgmtService() {
        return memberCardAccountMgmtService;
    }

    @EsbEIHttpWired
    public void setMemberCardAccountMgmtService(MemberCardAccountMgmtService memberCardAccountMgmtService) {
        this.memberCardAccountMgmtService = memberCardAccountMgmtService;
    }

    public MemberRollbackAccountService getMemberRollbackAccountService() {
        return memberRollbackAccountService;
    }

    @EsbEIHttpWired
    public void setMemberRollbackAccountService(MemberRollbackAccountService memberRollbackAccountService) {
        this.memberRollbackAccountService = memberRollbackAccountService;
    }

    public OrderPointUseService getOrderPointUseService() {
        return orderPointUseService;
    }

    @EsbEIHttpWired
    public void setOrderPointUseService(OrderPointUseService orderPointUseService) {
        this.orderPointUseService = orderPointUseService;
    }
}
